﻿using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace GeFamily
{
    public partial class BarUserControl : UserControl
    {
        public int Row { get; set; }

        public int Column { get; set; }

        protected override void OnCreateControl()
        {
            const int padding = 2;
            const int width = 50;
            const int height = 20;

            SuspendLayout();

            for (var i = 0; i < Row; i++)
            {
                for (var j = 0; j < Column; j++)
                {
                    var textBox = new TextBox
                                      {
                                          Size = new Size(width, height),
                                          Location = new Point((width + padding)*j, (height + padding)*i)
                                      };
                    Controls.Add(textBox);
                }
            }
            Size = new Size((width + padding) * Column, (height + padding) * Row);
            ResumeLayout(true);
        }

        public int [] GetData()
        {
            var data=new List<int>();
            for (var i = 0; i < Controls.Count; i++)
            {
                if (Controls[i] is TextBox)
                {
                    int x;
                    if(int.TryParse(Controls[i].Text,out x))
                    {
                        data.Add(x);
                    }
                }
            }
            return data.ToArray();
        }

        public void SaveData()
        {
            var data = new string[Row*Column];
            for (var i = 0; i < Controls.Count; i++)
            {
                if(Controls[i] is TextBox)
                {
                    data[i] = Controls[i].Text;
                }
            }
            var fs = new FileStream(Application.StartupPath+ "\\data.bin", FileMode.Create);
            var binaryFormatter=new BinaryFormatter();  
            binaryFormatter.Serialize(fs,data);
            fs.Flush();
            fs.Close();
        }

        public void LoadData()
        {
            if (File.Exists("data.bin"))
            {
                var fs = new FileStream(Application.StartupPath + "\\data.bin", FileMode.Open);
                var binaryFormatter = new BinaryFormatter();
                var data = (string[]) binaryFormatter.Deserialize(fs);
                fs.Close();

                for (var i = 0; i < data.Length; i++)
                {
                    if (Controls[i] is TextBox)
                    {
                        Controls[i].Text=data[i];
                    }
                }
            }

        }
    }
}